package com.example.casper.jnuexperiment2025;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.casper.jnuexperiment2025.Data.Book;
import com.example.casper.jnuexperiment2025.Data.DataBank;

import java.util.ArrayList;
import java.util.Objects;

public class BookListFragment extends Fragment {

    private ActivityResultLauncher<Intent> bookLauncher;
    private int longClickPosition;
    private ArrayList<Book> books;
    private BookItemAdapter adapter;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_book_list, container, false);

        RecyclerView bookRecyclerView = view.findViewById(R.id.recycler_view_my_books);
        bookRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));

        books = new DataBank().load(getContext());

        if (books.isEmpty()) {
            books.add(new Book("软件项目管理案例教程（第3版）", R.drawable.book_2, 35.0));
            books.add(new Book("无名之书", R.drawable.book_no_name, 45.5));
            books.add(new Book("信息安全数学基础（第2版）", R.drawable.book_1, 68));
        }

        adapter = new BookItemAdapter(books);
        bookRecyclerView.setAdapter(adapter);

        registerForContextMenu(bookRecyclerView);

        bookLauncher = registerForActivityResult(
                new ActivityResultContracts.StartActivityForResult(),
                result -> {
                    if (result.getResultCode() == getActivity().RESULT_OK) {
                        Intent data = result.getData();
                        assert data != null;
                        String name = data.getStringExtra("name");
                        double price = Double.parseDouble(Objects.requireNonNull(data.getStringExtra("price")));
                        int type = data.getIntExtra("type", 0);

                        if (type == 0) { // 添加
                            books.add(new Book(name, R.drawable.book_1, price));
                            adapter.notifyItemInserted(books.size() - 1);
                            new DataBank().save(books, getContext());
                        } else { // 更新
                            books.get(longClickPosition).setBookname(name);
                            books.get(longClickPosition).setPrice(price);
                            adapter.notifyItemChanged(longClickPosition);
                            new DataBank().save(books, getContext());
                        }
                    }
                });

        return view;
    }

    @Override
    public boolean onContextItemSelected(@NonNull MenuItem item) {
        Book b = books.get(longClickPosition);

        switch (item.getItemId()) {
            case 0: // 添加
                Intent addIntent = new Intent(getContext(), BookActivity.class);
                addIntent.putExtra("type", 0);
                bookLauncher.launch(addIntent);
                return true;

            case 1: // 更新
                Intent editIntent = new Intent(getContext(), BookActivity.class);
                editIntent.putExtra("type", 1);
                editIntent.putExtra("name", b.get_bookname());
                editIntent.putExtra("price", b.get_price());
                bookLauncher.launch(editIntent);
                return true;

            case 2: // 删除
                new AlertDialog.Builder(getContext())
                        .setMessage("确定删除？")
                        .setPositiveButton("是", (d, w) -> {
                            books.remove(longClickPosition);
                            adapter.notifyItemRemoved(longClickPosition);
                            new DataBank().save(books, getContext());
                        })
                        .setNegativeButton("否", null)
                        .show();
                return true;
        }
        return super.onContextItemSelected(item);
    }

    // BookItemAdapter 类保持不变，从原来的 Activity 中复制过来
    public static class BookItemAdapter extends RecyclerView.Adapter<BookItemAdapter.ViewHolder> {
        // 这里保持原来的 BookItemAdapter 代码不变
        // 只需要修改 context 获取方式

        private final ArrayList<Book> bookArrayList;

        public static class ViewHolder extends RecyclerView.ViewHolder {
            private final TextView textViewItemName;
            private final ImageView imageViewItem;
            private final TextView textViewItemPrice;

            public ViewHolder(View viewRowRoot) {
                super(viewRowRoot);
                textViewItemName = viewRowRoot.findViewById(R.id.text_view_book_name);
                imageViewItem = viewRowRoot.findViewById(R.id.image_view_book_cover);
                textViewItemPrice = viewRowRoot.findViewById(R.id.text_view_book_price);

                itemView.setOnLongClickListener(v -> {
                    ((BookListFragment.BookItemAdapter) v.getTag()).setLongClickPosition(getAdapterPosition());
                    return false;
                });

                itemView.setOnCreateContextMenuListener((menu, v, menuInfo) -> {
                    menu.add(0, 0, 0, "添加");
                    menu.add(0, 1, 0, "更新");
                    menu.add(0, 2, 0, "删除");
                });
            }

            public TextView getTextViewItemName() { return textViewItemName; }
            public ImageView getImageViewItem() { return imageViewItem; }
            public TextView getTextViewItemPrice() { return textViewItemPrice; }
        }

        public BookItemAdapter(ArrayList<Book> books) {
            bookArrayList = books;
        }

        @NonNull
        @Override
        public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View viewRowRoot = LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.book_item_row, parent, false);
            ViewHolder holder = new ViewHolder(viewRowRoot);
            viewRowRoot.setTag(this); // 用于在ViewHolder中访问adapter
            return holder;
        }

        @SuppressLint("SetTextI18n")
        @Override
        public void onBindViewHolder(ViewHolder viewHolder, final int position) {
            viewHolder.getTextViewItemName().setText(bookArrayList.get(position).get_bookname());
            viewHolder.getImageViewItem().setImageResource(bookArrayList.get(position).get_imageResourceId());
            viewHolder.getTextViewItemPrice().setText("￥" + bookArrayList.get(position).get_price());
        }

        @Override
        public int getItemCount() {
            return bookArrayList.size();
        }

        public void setLongClickPosition(int position) {
            // 这里需要通过Fragment来设置longClickPosition
            // 需要修改一下逻辑，可以通过接口回调
        }
    }
}
